<template>
  <el-row>
    <el-upload
      class="avatar-uploader"
      action="http://localhost:8080/"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload">
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <el-button @click="upLoad">
      上传头像
    </el-button>
  </el-row>
</template>
<script>
import axios from "axios";
const ERR_OK = 1;
export default {
  data() {
    return {
      imageUrl: "",
      file: {},
      huser_id: 0,
    };
  },
  created() {
    let msg = localStorage.getItem("loginMsg");
    this.huser_id = JSON.parse(msg).huser_id;
  },
  methods: {
    upLoad() {
      if (!this.imageUrl) {
        this.$notify({
          title: "提示",
          message: "请先添加头像！",
          position: "top-left"
        });
      }
      const url = "api/bugs/uploadPic.html";
      const param = {
        pic: this.imageUrl,
        pic_name: this.file.name,
        huser_id: this.huser_id
      };
      axios
        .post(url, param)
        .then(res => {
          if (parseInt(res.data.code) === 1) {
            sessionStorage.setItem('avatar', res.data.data.imgPath)
            this.$notify({
              title: "提示",
              message: "头像上传成功，请刷新页面",
              position: "top-left"
            });
          }
        })
        .catch(e => {
          this.$notify({
            title: "提示",
            message: "头像上传失败",
            position: "top-left"
          });
        });
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      let that = this;
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      var reader = new FileReader();
      this.file = file;
      reader.readAsDataURL(file);
      reader.onload = function () {
        //读取完成后，数据保存在对象的result属性中
        that.imageUrl = this.result;
      };

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return false;
    }
  }
};
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 200px;
  height: 200px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
